package jp.tuyano.sample.server;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import jp.tuyano.core.PMF;
import jp.tuyano.sample.client.form.ReferenceForm;
import jp.tuyano.sample.client.search.SearchService;
import jp.tuyano.sample.server.entity.Employee;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class SearchServiceImpl extends RemoteServiceServlet implements
        SearchService {

    private static final long serialVersionUID = 1L;

    private static final Logger log = Logger.getLogger(
            SearchServiceImpl.class.getName());

    public List<ReferenceForm> searchEmployee(String queryString) {

        PersistenceManager pm = PMF.get().getPersistenceManager();
        StringBuilder qsBuilder = new StringBuilder("SELECT FROM ").append(
                Employee.class.getName());
        if (queryString.length() != 0) {
            qsBuilder.append(" ").append(queryString);
        }

        String qr = qsBuilder.toString();

        log.info("[INFO] QUERY : " + qr);

        Query query = pm.newQuery(qr);

        @SuppressWarnings("unchecked")
        List<Employee> result = (List<Employee>) query.execute();

        List<ReferenceForm> dispList = new ArrayList<ReferenceForm>();

        for (Employee emp: result) {
            ReferenceForm form = new ReferenceForm(emp.getId(),
                    emp.getLastName(), emp.getFirName(), emp.getSex(),
                    emp.getEnterDate());
            dispList.add(form);
        }
        return dispList;
    }

}
